package order

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/logic/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/order/rpc/orderclient"
	"mall/service/product/rpc/productclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CloseOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCloseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CloseOrderLogic {
	return &CloseOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CloseOrderLogic) CloseOrder(
	req *types.CloseOrderReq,
	headers *[]*types.Header,
) (resp *types.CloseOrderResp, err error) {
	if req.Id == nil || *req.Id == 0 {
		return nil, resultx.NewErrCode(resultx.ORDER_ID_REQUIRED)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	preload := "order:Id,OrderType"
	preload += ";orderItem:Id,SkuId,Quantity"
	eagerLoad := "order:orderItem"
	var filters []string
	filters = append(filters, "Id,equalTo:"+strconv.FormatInt(int64(*req.Id), 10))
	filters = append(filters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))
	filters = append(filters, "TradeState,equalTo:"+strconv.FormatInt(int64(globalkey.OrderTradeStateNotPay), 10))
	var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini

	res, err := l.svcCtx.OrderRpc.GetOrderById(l.ctx, &orderclient.BaseIdReq{
		Preload:    pointy.GetPointer(preload),
		EagerLoad:  pointy.GetPointer(eagerLoad),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(platformId),
	})
	if err != nil {
		logx.Errorw("CloseOrder GetOrderById err", logx.Field("detail", err.Error()))
		return nil, err
	}

	if res == nil || res.Id == nil || *res.Id == 0 {
		return nil, resultx.NewErrCode(resultx.ORDER_PARAM_INVALID)
	}

	if len(res.Skus) > 0 && *res.OrderType != globalkey.OrderTypeVirtual {
		var stocks []*productclient.ProductVariationStock
		for _, v := range res.Skus {
			if v.SkuId != nil && v.Quantity != nil && *v.SkuId > 0 && *v.Quantity > 0 {
				stocks = append(stocks, &productclient.ProductVariationStock{
					Id:    *v.SkuId,
					Stock: *v.Quantity,
				})
			}
		}
		if len(stocks) > 0 {
			_, err = l.svcCtx.ProductRpc.SubtractStockRevert(l.ctx, &productclient.CheckAndSubtractStockReq{
				Data: stocks,
			})
			if err != nil {
				logx.Errorw("CloseOrder SubtractStockRevert err", logx.Field("detail", err.Error()))
				// return &types.CloseOrderResp{
				// 	Msg: "操作失败",
				// }, nil
			}
		}
	}

	tradeState := pointy.GetPointer(globalkey.OrderTradeStateUserCancelled)
	_, err = l.svcCtx.OrderRpc.UpdateTradeState(l.ctx, &orderclient.UpdateTradeStateReq{
		Id:         res.Id,
		TradeState: tradeState,
	})
	if err != nil {
		logx.Errorw("CloseOrder UpdateTradeState err", logx.Field("detail", err.Error()))
		return nil, err
	}

	option := util.GetOptionByStatus(tradeState)

	return &types.CloseOrderResp{
		Option: &types.TradeInfoFragment{
			TradeState:     tradeState,
			TradeStateText: util.GetTradeStateText(tradeState),
			CanCancel:      option.CanCancel,
			CanPay:         option.CanPay,
			CanRefund:      option.CanRefund,
			CanRemind:      option.CanRemind,
			CanTrack:       option.CanTrack,
			CanConfirm:     option.CanConfirm,
			CanInvoice:     option.CanInvoice,
			CanRemove:      option.CanRemove,
		},
	}, nil
}
